import dict from './dict';
import logger from './logger';
import fs from '@ohos.file.fs';
import window from '@ohos.window';
import request from '@ohos.request';
import cryptoJS from '@ohos/crypto-js';
import promptAction from '@ohos.promptAction';
import common from '@ohos.app.ability.common';
import { chipType } from '../models/enums/chipType';
import memoryImage from '../models/cards/memoryImage';

class utils {
  readonly COLOR_WHITE = '#ffffff';
  readonly COLOR_BLACK = '#000000';
  readonly COLOR_LIKE_WHITE ='#f7f7f7';

  getChipTypes(supportChip: chipType): Array<string> {
    let chips = [];
    if (supportChip === chipType.Arm)
      chips.push('Arm');
    if (supportChip === chipType.Arm64)
      chips.push('Arm64');
    if (supportChip === chipType.RiscV)
      chips.push('Risc-V');
    if (supportChip === chipType.LoongArch)
      chips.push('LoongArch');
    if (supportChip === chipType.X86)
      chips.push('X86');
    if (supportChip === chipType.X64)
      chips.push('X64');
    return chips;
  }

  md5(str: string): string {
    return cryptoJS.MD5(str).toString();
  }

  getSize(id: string): Array<number> {
    var info = JSON.parse(getInspectorByKey(id));
    var rectStr = info.$rect.replace('][', ',')
      .replace('[', '')
      .replace(']', '')
      .replace(' ', '')
      .split(',');
    return [Number(rectStr[2]) - Number(rectStr[0]), Number(rectStr[3]) - Number(rectStr[1])];
  }

  isEmpty(obj: any): boolean {
    if (typeof obj == 'undefined' || obj == null || obj?.toString().trim() == '')
      return true;
    return false;
  }

  showPopup(msg: string, duration?: number) {
    if (this.isEmpty(duration))
      duration = 2000;
    promptAction.showToast({
      message: msg,
      duration: duration,
    });
  }

  setLayoutFullScreen(windowStage: window.WindowStage, statusBarColor: string, statusBarContentColor: string,
                      navigationBarColor: string, navigationBarContentColor: string) {
    let windowClass = null;
    windowStage.getMainWindow((err, data) => {
      if (err.code) return;
      windowClass = data;
      let isLayoutFullScreen = false;
      windowClass.setWindowLayoutFullScreen(isLayoutFullScreen);
      let sysBarProps = {
        statusBarColor: statusBarColor,
        statusBarContentColor: statusBarContentColor,
        navigationBarColor: navigationBarColor,
        navigationBarContentColor: navigationBarContentColor
      };
      windowClass.setWindowSystemBarProperties(sysBarProps);
    });
  }

  getRandomInt(randomNumber: number): number {
    let roundNumber: number = Math.round(Math.random() * dict.MULTIPLY_TEN);
    if (roundNumber === randomNumber)
      roundNumber = this.getRandomInt(randomNumber);
    return roundNumber;
  }

  buildMemoryImage(context: common.Context, urls: Array<string>): Promise<Array<memoryImage>> {
    let arr: Array<memoryImage> = [];
    return new Promise((resolve) => {
      try {
        for (var idx=0;idx< urls.length;idx++) {
          this.download(context, 0, urls[idx]).then((mi) => {
            arr.push(mi);
            if (arr.length == urls.length)
              resolve(arr);
          });
        }
      } catch (e) {
        logger.error(e);
        resolve(arr);
      }
    });
  }

  private download(context: common.Context, idx: number, url: string): Promise<memoryImage> {
    return new Promise((resolve) => {
      let tempDir = context.getApplicationContext().tempDir;
      var rnd = Math.floor((Math.random() * 100) + 1);
      let fileName = `file${Date.now()}${rnd}`;
      let tmpFile = `${tempDir}/${fileName}`;
      request.downloadFile(context, {
        url: url, filePath: tmpFile, enableMetered: true, enableRoaming: true
      }).then((task) => {
        task.on('complete', function callback() {
          fs.open(tmpFile).then((file) => {
            let info = new memoryImage(idx, file.fd, fileName);
            resolve(info);
          });
        });
        task.on('fail', function callBack(err) {
          logger.info('ArkTSCard download task failed. Cause:' + err);
          resolve(null);
        });
      }).catch((res) => {
        logger.error(res);
        resolve(null);
      });
    });
  }
}
export default new utils();